#include "board.h"
#include "log.h"
#include <stdio.h>
#include "bflb_gpio.h"
#include "bflb_mtimer.h"
#include "bflb_timer.h"

#include "74hc595.h"

#define PIN_CLK GPIO_PIN_13
#define PIN_SER GPIO_PIN_10
#define PIN_ST  GPIO_PIN_19

struct bflb_device_s* gpio;
struct bflb_device_s* timer0;

void delay_us(uint32_t us)
{
    bflb_mtimer_delay_us(us);
}

int gpio_set_data(uint8_t pin, uint8_t data)
{
    if (data) {
        bflb_gpio_set(gpio, pin);
    }
    else {
        bflb_gpio_reset(gpio, pin);
    }
    return 0;
}

int gpio_init(uint8_t pin, uint32_t cfgset)
{
    bflb_gpio_init(gpio, pin, cfgset);
}

void timer0_isr(int argc, void* argv)
{
    bool status = bflb_timer_get_compint_status(timer0, TIMER_COMP_ID_0);
    if (status) {
        bflb_timer_compint_clear(timer0, TIMER_COMP_ID_0);
        digit_dev_t* dev = (digit_dev_t*)argv;
        hc595_desplay(dev, -1234.567);
    }
}

int main(void)
{
    board_init();
    printf("74hc595 start!\n");

    gpio = bflb_device_get_by_name("gpio");
    digit_dev_t dev = {
        .pin_clk = PIN_CLK,
        .pin_ser = PIN_SER,
        .pin_st = PIN_ST,
        .delay_fun = delay_us,
        .set_dev_data = gpio_set_data,
        .gpio_init = gpio_init,
    };
    hc595_init(&dev);

    
    struct bflb_timer_config_s cfg;
    cfg.counter_mode = TIMER_COUNTER_MODE_PROLOAD;
    cfg.clock_source = TIMER_CLKSRC_XTAL;
    cfg.clock_div = 39;
    cfg.trigger_comp_id = TIMER_COMP_ID_0;
    cfg.comp0_val = 1000;
    cfg.preload_val = 0;

    timer0 = bflb_device_get_by_name("timer0");

    bflb_irq_attach(timer0->irq_num, timer0_isr, &dev);
    bflb_irq_enable(timer0->irq_num);

    bflb_timer_init(timer0, &cfg);

    bflb_timer_start(timer0);

    while (1) {
        bflb_mtimer_delay_ms(1000);
    }
    return 0;
}